import { _decorator, Component, instantiate, Label, Prefab, Node } from 'cc';
import Global from '../common/Global';
import { levelData, DigMap } from './levelData';
import { MatchDigit } from './MatchDigit';
import { loadPrefab, debounce } from './utils';
import { Statistic } from '../common/Statistic';
import { saveTravelResult } from '../common/Apis';
const { ccclass, property } = _decorator;
import { MultipleAudioControler } from '../logicalReasoning/MultipleAudioControler';

@ccclass('MatchstickMain')
export class MatchstickMain extends Component {
	level: number = 0; //从0 开始
	@property(Prefab)
	digPrefab: Prefab;
	debouncedFn: any = null;
	backupNode: Node = null;
	@property(Node)
	popup: Node = null;
	statistic: Statistic = new Statistic();
	player: MultipleAudioControler;
	onLoad(): void {
		if (!Global.gameOrderBy) {
			Global.gameOrderBy = 1;
		}
		this.backupNode = instantiate(this.node);
	}
	async start() {
		// let data = await loadPrefab('./matchstick/match-dig');
		// this.digPrefab = data;
		this.initData();
		this.player = this.node.getComponent(MultipleAudioControler);
		this.debouncedFn = debounce({ delay: 50 }, this.judgeResult);
	}

	initData() {
		this.level = Global.gameOrderBy - 1;
		console.log('this.level', this.level);

		let data = levelData[this.level];
		if (Array.isArray(data.digMap)) {
			data.digMap.forEach((digMap) => {
				this.createDigMatch(digMap);
			});
			this.showOperatorSymbol(true);
		} else {
			this.createDigMatch(data.digMap);
			this.showOperatorSymbol(false);
		}
		this.setTipTextContent(data.content);
	}
	showOperatorSymbol(bool: boolean) {
		let plus = this.node.getChildByName('plusSymbol');
		let equal = this.node.getChildByName('equalSymbol');
		if (this.level <= 2) {
			plus.active = false;
			equal.active = false;
		} else {
			plus.active = true;
			equal.active = true;
		}
		if (this.level <= 5) {
			plus.angle = 0;
			plus.children[0].active = true;
			plus.setPosition(-410, -154);
			equal.setPosition(124, -116);
		} else if (this.level <= 8) {
			//减法
			plus.angle = 0;
			plus.children[0].active = false;
		} else if (this.level <= 10) {
			//减法
			plus.angle = 0;
			plus.children[0].active = false;
			plus.setPosition(-141, -153);
			equal.setPosition(392, -116);
		} else if (this.level <= 13) {
			//乘法
			plus.angle = -45;
			plus.children[0].active = true;
			plus.setPosition(-410, -154);
			equal.setPosition(124, -116);
		} else if (this.level <= 16) {
			//加
			plus.angle = 0;
			plus.children[0].active = true;
			plus.setPosition(-410, -154);
			equal.setPosition(124, -116);
		} else {
			//减法
			plus.angle = 0;
			plus.children[0].active = false;
			plus.setPosition(-141, -153);
			equal.setPosition(392, -116);
		}
	}
	createDigMatch(digMap: DigMap) {
		let digNode = instantiate(this.digPrefab);
		if (digMap.name) {
			digNode.name = digMap.name;
		}
		let { x, y } = digMap.position;
		digNode.setPosition(x, y);
		let matchDig = digNode.getComponent(MatchDigit);
		matchDig.initData(digMap.digData);
		matchDig.digValue = digMap.digValue;
		digNode.setParent(this.node);
		digNode.setSiblingIndex(0);
	}
	setTipTextContent(text: string) {
		let tipNode = this.node.getChildByName('tipText');
		let label = tipNode.getComponent(Label);
		label.string = text;
	}
	digValueChanged() {
		this.debouncedFn();
	}
	judgeResult = () => {
		// 前三关只看数据
		if (this.level < 3) {
			let answer = levelData[this.level].answer;
			let dig = this.node.getComponentInChildren(MatchDigit);
			if (answer === dig.digValue) {
				this.saveResult(1);
				this.levelPassed();
			}
		} else {
			// 三关后比较等式
			let a = this.getMatchDigitCom('a');
			let b = this.getMatchDigitCom('b');
			let c = this.getMatchDigitCom('c');
			let d = this.getMatchDigitCom('d');
			let isEqual = this.isEqual(
				a?.digValue,
				b?.digValue,
				c?.digValue,
				d?.digValue
			);
			console.log('d', d);

			console.log('isEqual', isEqual);
			if (isEqual) {
				this.saveResult(1);
				this.levelPassed();
			} else {
				if (this.level >= 14) {
					// 游戏失败
					console.log('游戏失败');
				}
			}
		}
	};
	// 判断等式是否成立
	isEqual(a, b, c, d) {
		// if (!this.validateResult(a, b, c, d)) return;
		console.log('a,b,c,d', a, b, c, d);

		if (this.level <= 5) {
			if (this.hasIllegalDig([a, b, d])) return false;
			return a + b == this.getDecadeValue(c) + d;
		} else if (this.level <= 8) {
			if (this.hasIllegalDig([a, b, c])) return false;
			return a - b == c;
		} else if (this.level <= 10) {
			if (this.hasIllegalDig([b, c, d])) return false;
			return this.getDecadeValue(a) + b - c == d;
		} else if (this.level <= 13) {
			if (this.hasIllegalDig([a, b, c])) return false;
			return a * b == this.getDecadeValue(c) + d;
		} else if (this.level <= 16) {
			if (this.hasIllegalDig([a, b, d])) return false;
			return a + b == this.getDecadeValue(c) + d;
		} else {
			if (this.hasIllegalDig([b, c, d])) return false;
			return this.getDecadeValue(a) + b - c == d;
		}
	}
	getDecadeValue(n: number) {
		return (n == -1 ? 0 : n) * 10;
	}
	hasIllegalDig(arr: number[]) {
		return arr.some((dig) => dig === -1 || typeof dig !== 'number');
	}
	validateResult(...args) {
		return args.every((item) => typeof item?.digValue === 'number');
	}
	getMatchDigitCom(name: string) {
		let digValues = this.node.getComponentsInChildren(MatchDigit);
		return digValues.find((child) => child.node.name === name);
	}
	resetNodes() {
		this.backupNode.setParent(this.node.parent);
		this.node.destroy();
	}
	nextLevel() {
		this.popup.active = false;
		Global.gameOrderBy++;
		this.resetNodes();
	}
	levelPassed() {
		this.player.play('通关成功');
		this.popup.active = true;
	}
	// 上传游戏结果
	async saveResult(pass: number) {
		let levelId = Global.gameLevels?.find(
			(item) => item.orderBy === Global.gameOrderBy
		)?.levelId;
		if (!levelId) return;
		let body = {
			startTime: this.statistic.startTime,
			pass: pass,
			travelLevelId: levelId,
		};
		try {
			await saveTravelResult(body);
		} catch (error) {
			console.log('error', error);
		}
	}
	update(deltaTime: number) {}
}
